package com.self.smallma.myblogweb.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.self.smallma.myblogweb.common.utils.R;

import com.self.smallma.myblogweb.entity.UserEntity;
import com.self.smallma.myblogweb.service.UserService;
import com.self.smallma.myblogweb.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Controller

public class RegisterController {

    @Autowired
    UserService userService;
    @GetMapping("/admin/reg")
    public String reg(HttpSession session){
        List<UserEntity> list = userService.list();
        session.setAttribute("userList",list);
        return "admin/register";
    }

    @PostMapping("/admin/register")
    public String  registerOK(@Valid RegisterVo registerVo){

        System.out.println("***********************");
        //注册成功，回到首页
        int result =  userService.register(registerVo);
        if (result==1){
            return "redirect:/index.html";
        }else {
            System.out.println("注册失败");
            return "admin/register";
        }

    }

    @ResponseBody
    @RequestMapping("/checkUser")
    public R checkUserName(@RequestParam("username") String username){
        System.out.println("------------------------------");
        //判断用户名是否合法
       String regx = "(^[a-zA-Z0-9_-]{3,16}$)|(^[\\u2E80-\\u9FFF]{2,6})";
       //匹配正则表达式
       if (!username.matches(regx)){
            return R.error("用户名必须是3-16位数字或字母的组合或者2-6位中文");
       }

       //数据库重复校验
        List<UserEntity> userEntities = userService.list(new QueryWrapper<UserEntity>()
                .eq("username", username));
        if (userEntities.size()==0){
            return R.ok("用户名可用");
        }else {
            return R.error("用户名重复");
        }

    }

    @ResponseBody
    @RequestMapping("/checkemail")
    public R checkEmail(@RequestParam("email") String email){
        String regx = "^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$";
        if (!email.matches(regx)){
            return R.error("邮箱格式不合法");
        }
        List<UserEntity> list = userService.list(new QueryWrapper<UserEntity>().eq("email", email));
        if (list.size()==0){
            return R.ok("邮箱可用");
        }else {
            return R.error("邮箱重复");
        }
    }
}
